from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView
from meiduo_mall.libs.captcha.captcha import captcha
import logging
from django_redis import get_redis_connection
from verifications import constants

from rest_framework.generics import GenericAPIView
from .serializers import ImageCodeCheckSerializer
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')

# Create your views here.
# 发送图片验证码
# GET / image_codes / (?P < image_code_id > [\w -]+) /
class ImageCodeView(APIView):
    def get(self, request, image_code_id):

        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return HttpResponse(image, content_type='image/jpg')

# 发送短信验证码, 校验图片验证码
# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SMSCodeView(GenericAPIView):
    serializer_class = ImageCodeCheckSerializer
    def get(self, request, mobile):
        # 使用序列化器反序列化校验
        serializer = self.get_serializer(data=request.query_params)
        #开启校验
        serializer.is_valid(raise_exception=True)

        sms_code = "%06d" % random.randint(0, 999999)
        logger.info(sms_code, '*****************')

        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        # 保存验证码
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        #保存发送验证码间隔
        pl.setex('sms_flag%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        expire = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        # CCP().send_template_sms(mobile, [sms_code, expire], 1)
        send_sms_code.delay(mobile, sms_code, expire)
        return Response({'message': 'OK'})























